package com.foxconn.AppDownload.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.foxconn.AppDownload.domain.AppInfo;
import com.foxconn.AppDownload.domain.AppMenu;
import com.foxconn.AppDownload.domain.SmartFactoryAppInfo;
import com.foxconn.AppDownload.domain.ZxingLogoConfig;
import com.foxconn.AppDownload.service.AppMenuService;
import com.foxconn.AppDownload.service.AppService;
import com.foxconn.AppDownload.service.SmartFactoryInfoService;
import com.foxconn.AppDownload.util.Consts;
import com.foxconn.AppDownload.util.RetObject;
import com.foxconn.AppDownload.util.Utils;
import com.foxconn.AppDownload.util.ZXingCode;
import com.google.zxing.BarcodeFormat;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import java.util.regex.Pattern;

/**
 * @author zengdong
 * @version 1.0
 * @date 2023/12/19 15:47
 */
@Controller
public class LoginController {

    public static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private AppService appService;

    @Autowired
    private AppMenuService appMenuService;

    @Autowired
    private SmartFactoryInfoService smartFactoryInfoService;

    //跳轉到下載頁面
    @RequestMapping("download") //前端需要iconUrl appName qrcodePathList lastVersion clientType
    public String toDownloadPage(Model model, int id, String iconUrl){
        String appName = "";
        //用于生成二维码的路径
        String qrcodePath = "";
        //用于传递给前端的二维码路径
        String qrcodePath2 = "";
        //下載app包的路径
        String downloadAppPath = "";
        //版本號 -最新
        String lastVersion = "";
        //logoPath
        String logoPath = Consts.headLogoPath + iconUrl;  //本地： "src/main/webapp/" + iconUrl 220.99 測試：C:\Program Files\Tomcat 8.5\webapps  //txz正式：/usr/local/software/tomcat4_1/apache-tomcat-9.0.65/webapps/AppDownload/
        //版本類型
        String clientType = "";
        String editDate = "";
        //二維碼存儲路徑
        HashMap<String, String> qrCodePathMap = new HashMap<>();
        //下載包地址
        HashMap<String, String> downloadAppPathMap = new HashMap<>();
        downloadAppPathMap.put("Android","0");
        downloadAppPathMap.put("iOS","0");

        //id==1 智能工廠APP特殊處理
        if (id==1){
            model.addAttribute("iconUrl",iconUrl); //logo 路徑
            model.addAttribute("appName","智能工厂APP平台");
            List<SmartFactoryAppInfo> smartFactoryAppInfoList = smartFactoryInfoService.list(new QueryWrapper<SmartFactoryAppInfo>().eq("SYSTEM_CODE", 0).orderByDesc("VERSION_CODE").last("LIMIT 2"));
            for (SmartFactoryAppInfo smartFactoryAppInfo : smartFactoryAppInfoList) {
                editDate = smartFactoryAppInfo.getEditDate();
                lastVersion = smartFactoryAppInfo.getLastVersion();
                //下載app包的路径
                downloadAppPath = smartFactoryAppInfo.getDownloadUrl();
                clientType = smartFactoryAppInfo.getClientType();
                //如果版本為Android
                if (clientType.equals("Android")){
                    qrcodePath = Consts.headLogoPath + "image/QRCode/qrcode-download-and.png"; //"src/main/webapp/image/QRCode/qrcode-download-and.png"
                    qrcodePath2 = "image/QRCode/qrcode-download-and.png";
                }else {//為 iOS
                    qrcodePath = Consts.headLogoPath + "image/QRCode/qrcode-download-ios.png"; //"src/main/webapp/image/QRCode/qrcode-download-ios.png"
                    qrcodePath2 = "image/QRCode/qrcode-download-ios.png";
                }
                //調用生成二維碼的方法
                Utils.createQRCode(downloadAppPath,300,logoPath,qrcodePath);
                qrCodePathMap.put(clientType,qrcodePath2);
                downloadAppPathMap.put(clientType,downloadAppPath);
            }
            model.addAttribute("editDate",editDate.substring(0,10));
            model.addAttribute("lastVersion",lastVersion); //app 最新版本號
            model.addAttribute("qrCodePathMap",qrCodePathMap);  //下載的二維碼路徑
            model.addAttribute("downloadAppPathMap",downloadAppPathMap);//下載包路徑
            return "/WEB-INF/download";
        }

        //獲取app信息
        List<AppInfo> appList = appService.list(new QueryWrapper<AppInfo>().eq("APP_DOWNLOAD_ID", id).eq("DEL_FLAG",0));
        //生成二維碼
        for (AppInfo appInfo : appList) {
            appName = appInfo.getAppName();
            editDate = appInfo.getEditDate();
            lastVersion = appInfo.getLastVersion();
            //下載app包的路径
            downloadAppPath = appInfo.getDownloadUrl();
            clientType = appInfo.getClientType();
            String iconUrl1 = appInfo.getIconUrl();
            String PName = iconUrl1.substring(iconUrl1.lastIndexOf("/")+1);
            //如果版本為Android
            if (clientType.equals("Android")){
                qrcodePath = Consts.headLogoPath + "image/QRCode/qrcode-download-and-"+PName; //"src/main/webapp/image/QRCode/qrcode-download-and.png"
                qrcodePath2 = "image/QRCode/qrcode-download-and-"+PName;
            }else {//為 iOS
                qrcodePath = Consts.headLogoPath + "image/QRCode/qrcode-download-ios-"+PName; //"src/main/webapp/image/QRCode/qrcode-download-ios.png"
                qrcodePath2 = "image/QRCode/qrcode-download-ios-"+PName;
            }
            //調用生成二維碼的方法
            Utils.createQRCode(downloadAppPath,300,logoPath,qrcodePath);
            qrCodePathMap.put(clientType,qrcodePath2);
            downloadAppPathMap.put(clientType,downloadAppPath);
        }
        model.addAttribute("iconUrl",iconUrl); //logo 路徑
        model.addAttribute("appName",appName);
        model.addAttribute("qrCodePathMap",qrCodePathMap);  //下載的二維碼路徑
        model.addAttribute("lastVersion",lastVersion); //app 最新版本號
        model.addAttribute("clientType",clientType);
        model.addAttribute("editDate",editDate.substring(0,10));
        model.addAttribute("downloadAppPathMap",downloadAppPathMap);//下載包路徑

        return "/WEB-INF/download";
    }

    //登陸
    @RequestMapping("login1")
    @ResponseBody
    public Object login(int id, String password, HttpSession session, HttpServletRequest request){
        RetObject retObject = new RetObject();
        //根據id 查詢數據庫裡面對應的App密碼
        AppMenu appMenu = appMenuService.getOne(new QueryWrapper<AppMenu>().eq("APPID",id).eq("DEL_FLAG",0));
        if (appMenu==null){
            retObject.setCode(0);
            retObject.setMessage("應用錯誤！");
            return retObject;
        }
        if (!appMenu.getPwd().equals(password)){
            retObject.setCode(0);
            retObject.setMessage("密碼錯誤！");
            return retObject;
        }
        // 读取 X-Forwarded-For 请求头
        String forwardedFor = request.getHeader("X-Forwarded-For");

        // 解析终端的 IP 地址
        String clientIp = null;
        if (forwardedFor != null && !forwardedFor.isEmpty()) {
            String[] ips = forwardedFor.split(",");
            clientIp = ips[ips.length - 1].trim();
        }
        if (clientIp == null || clientIp.isEmpty()) {
            clientIp = request.getRemoteAddr();
        }

        Properties properties = new Properties();
        try (FileInputStream fis = new FileInputStream(Consts.configPath)) {
            properties.load(fis);
            String[] ips = properties.getProperty("server.ip").split(",\\s*");
            boolean isMatched = false;
            for (String ip : ips) {
                if (Pattern.matches(ip.replace(".", "\\.").replace("*", "[0-9]*"), clientIp)) {
                    isMatched = true;
                    break;
                }
            }
            //如果是外網
            if (!isMatched){
                //如果是智能工廠
                if (appMenu.getAppId()==1){
                    retObject.setCode(1);
                    retObject.setMessage("登陸成功！");
                    session.setAttribute(Consts.LOGIN_EVIDENCE,appMenu.getAppId());
                    return retObject;
                }
                List<AppInfo> applist = appService.list(new QueryWrapper<AppInfo>().eq("APP_DOWNLOAD_ID", appMenu.getAppId()).eq("DEL_FLAG", 0));
                AppInfo app = applist.get(0);
                logger.error("appName : "+app.getAppName());
                //應用類型只能內網下載
                if (app.getNetwork()==1||app.getNetwork()==2||app.getNetwork()==3){
                    retObject.setCode(0);
                    retObject.setMessage("此应用仅内部使用，当前无权限！(400)");
                    return retObject;
                }
                if (app.getNetwork()==4){
                    retObject.setCode(1);
                    retObject.setMessage("登陸成功！");
                    session.setAttribute(Consts.LOGIN_EVIDENCE,appMenu.getAppId());
                    return retObject;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            retObject.setCode(0);
            retObject.setMessage("出现错误，请稍后！");
            return retObject;
        }
        retObject.setCode(1);
        retObject.setMessage("登陸成功！");
        session.setAttribute(Consts.LOGIN_EVIDENCE,appMenu.getAppId());
        return retObject;
    }

    //跳转到登录页面
    @RequestMapping("login")
    public String toLoginPage(Model model, int id, HttpServletRequest request){
        AppMenu appMenu = appMenuService.getOne(new QueryWrapper<AppMenu>().eq("APPID",id).eq("DEL_FLAG",0));
        //二维码跳转的路径
        String loginPageUrl = request.getScheme()+"://"+request.getServerName()+":"+	request.getServerPort()+request.getContextPath()+"/"+ appMenu.getLoginPageUrl();

        //app logo path
        String logoPath = Consts.headLogoPath + appMenu.getIconUrl(); //"src/main/webapp/" + appMenu.getIconUrl()
        String qrcodePath = Consts.headLogoPath + "image/QRCode/qrcode-toLogin.png"; //"src/main/webapp/image/QRCode/qrcode-toLogin.png"
        //生成二维码
        Utils.createQRCode(loginPageUrl,300,logoPath,qrcodePath);
        //设置二维码路径 -返回给前端
        appMenu.setQrCodePath("image/QRCode/qrcode-toLogin.png");
        appMenu.setIconUrl(appMenu.getIconUrl());
        model.addAttribute("app",appMenu);
        return "/WEB-INF/login";
    }


    @GetMapping("/") //入口
    public String index(){
        return "redirect:/index?id=1";
    }

    @RequestMapping("index") //跳转到首页
    public String toIndex(Model model, int id){
        //獲取根路徑
//        String path = LoginController.class.getResource("/").getPath();
//        logger.error(path);
        AppMenu appMenu = appMenuService.getOne(new QueryWrapper<AppMenu>().eq("APPID",id).eq("DEL_FLAG",0));
        //二维码跳转的路径
        String loginPageUrl = Consts.headLoginPath + appMenu.getLoginPageUrl(); //本地：appMenu.getLoginPageUrl() 220.99:"https://facecd.foxconn.com/AppDownload/" + appMenu.getLoginPageUrl() txz:"https://txz.foxconn.com:8080/" + appMenu.getLoginPageUrl()

        //app logo path
        String logoPath = Consts.headLogoPath + appMenu.getIconUrl(); //"src/main/webapp/" + appMenu.getIconUrl()
        String qrCodeName = logoPath.substring(logoPath.lastIndexOf("/")+1);
        String qrcodePath = Consts.headLogoPath + "image/QRCode/qrcode-login-"+qrCodeName; //"src/main/webapp/image/QRCode/qrcode-login-"+qrCodeName
        //生成二维码
        Utils.createQRCode(loginPageUrl,300,logoPath,qrcodePath);
        //设置二维码路径 -返回给前端
        appMenu.setQrCodePath("image/QRCode/qrcode-login-"+qrCodeName);

        //查找如果只有一个平台的话，是啥平台
        if (appMenu.getClientTypeCount()==1){
            String clientType = appService.getOne(new QueryWrapper<AppInfo>().eq("APP_DOWNLOAD_ID", id).eq("DEL_FLAG",0)).getClientType();
            appMenu.setClientType(clientType);
        }
        model.addAttribute("app",appMenu);
        //查询所有的应用
        List<AppMenu> appMenuList = new ArrayList<>();
        if (id==1){
            appMenuList = appMenuService.list(new QueryWrapper<AppMenu>().eq("DEL_FLAG",0).ne("APPID",1));
        }
        model.addAttribute("appList",appMenuList);
        return "index1";
    }

    /**
    @RequestMapping("toIndex") //
    @ResponseBody
    public Object index(Model model, @RequestParam Map<String, Object> params, HttpServletRequest request) {
        RetObject retObject = new RetObject();
        HashMap<String, Object> retMap = new HashMap<>();
        int id = Integer.valueOf((String)params.get("id"));
        //如果id=0 表示是智能工厂平台 查询智能工厂的信息
        List<SmartFactoryAppInfo> smartFactoryAppInfos = null;  //初始化值为null
        AppInfo appInfo = null;
        List<AppInfo> appInfoList = null;
        if (id==0){
            smartFactoryAppInfos = smartFactoryInfoService.list(new QueryWrapper<SmartFactoryAppInfo>().eq("SYSTEM_CODE", 0).orderByDesc("VERSION_CODE").last("LIMIT 2"));
            retMap.put("appInfo",smartFactoryAppInfos);
        }else {
            appInfo = appService.getById(id);
            //排除不想要的应用
            if (appInfo.getTestVersion()==1||!appInfo.getClientType().equals("Android")||!appInfo.getClientType().equals("iOS")){
                retObject.setCode(0);
                retObject.setMessage("该应用不存在！");
                return retObject;
            }
            //获取应用名称
            String appName = appInfo.getAppName();
            //根据应用名称捞取数据
            appInfoList = appService.list(new QueryWrapper<AppInfo>().eq("APPNAME", appName));
            for (AppInfo appInfo1 : appInfoList) {
                //设置logo路径
                appInfo1.setIconUrl(appInfo1.getIconUrl().substring(1));
                //生成二维码
                //判断是ios|android
                String url = appInfo1.getLoginPageUrl(); //二维码跳转的路径
                String qrcodePath = "";
                String logoPath = "";
                if (appInfo1.getClientType().equals("iOS")){
                    qrcodePath = "src/main/webapp/images/QRCode/qrcode-ios.png";//二维码本地存放路径
                    logoPath = "src/main/webapp"+appInfo1.getIconUrl(); //app logo path
                    Utils.createQRCode(url,300,qrcodePath,logoPath);
                    //设置二维码路径 -返回给前端
                    appInfo1.setQrCode("./images/QRCode/qrcode-ios.png");
                }else {
                    qrcodePath = "src/main/webapp/images/QRCode/qrcode-and.png";//二维码本地存放路径
                    logoPath = "src/main/webapp"+appInfo1.getIconUrl(); //app logo path
                    Utils.createQRCode(url,300,qrcodePath,logoPath);
                    //设置二维码路径 -返回给前端
                    appInfo1.setQrCode("./images/QRCode/qrcode-and.png");
                }
            }
            retMap.put("appInfo",appInfoList);
        }
        retObject.setCode(1);
        retObject.setMessage("success!");
        retObject.setObj(retMap);

        return retObject;//
    }
**/

    /**
     * 生成二维码图片
     * @param content   url链接
     * @param size      图片大小
     * @param request
     * @param response
     */
    @RequestMapping("/createQRCode")
    public void createQRCode(String content, String logoPath,
                              Integer size,
                              HttpServletRequest request,
                              HttpServletResponse response) {
        if(StringUtils.isNotBlank(content)){
            if(size==null){
                size=100;
            }
            File logo=new File("src/main/webapp/"+logoPath);
            response.setContentType("image/png");
            try {
                //使用方式
                ZXingCode zp =  ZXingCode.getInstance();
                BufferedImage bim = zp.getQRCODEBufferedImage(content, BarcodeFormat.QR_CODE, size, size,
                        zp.getDecodeHintType());
                BufferedImage aim = zp.addLogoQRCode(bim, logo, new ZxingLogoConfig());
                ImageIO.write(aim, "png", response.getOutputStream());

                //如果是只要生成到本地文件夹 用以下写法
                //File file=new File("存放的绝对路径，例：D://xxx.jpg");
                //ImageIO.write(bim, "png", file);
            } catch (Exception e) {
                //e.printStackTrace();
            }
        }
    }


}
